package complexity;

import java.util.Iterator;

public class Queue<T> implements Iterable<T>{
    private int N;
    private Node head;
    private Node last;
    public Queue() {
        this.N = 0;
        this.head=new Node(null,null);
        this.last=null;
    }
    public boolean isEmpty(){
        return this.N==0;
    }
    public int size(){
        return this.N;
    }
    public T dequeue(){
        if (isEmpty()){
            last=null;
            return null;
        }
        Node oldNode = this.head.next;
        this.head.next = oldNode.next;
        this.N--;
        //当队列滞空时尾节点设置为空
        if (isEmpty()){
            this.last=null;
        }
        return oldNode.data;
    }
    public void enqueue(T t){
       if (this.last==null){
           this.last= new Node(t,null);
           this.head.next=this.last;
       }else {
           Node oldLast = this.last;
           this.last = new Node(t,null);
           oldLast.next=last;
       }
       this.N++;
    }
    private class Node{
        private T data;
        private Node next;
        public Node(T data,Node next) {
            this.next = next;
            this.data = data;
        }
    }
    @Override
    public Iterator<T> iterator() {
        return new IQueue();
    }
    private class IQueue implements Iterator{
        private Node node ;
        private IQueue(){
            this.node=head;
        }
        @Override
        public boolean hasNext() {
            return node.next!=null;
        }

        @Override
        public Object next() {
            node=node.next;
            return node.data;
        }
    }
}
